function [V, rotM] = sw_rot(rotAxis, rotAngle, V)
% [V, rotM] = SW_ROT(rotAxis, rotAngle, {V}) rotates vectors in V around
% rotAxis by rotAngle radian.
%
% rotAxis   Axis of rotation, dimensions are [1 3].
% rotAngle  Angle of rotation in radian.
% V         Matrix of 3D vectors, dimensions are [3 N], optional.
%
% Output:
% V         Rotated vectors, dimensions are [3 N].
% rotM      Rotation matrix, dimensions are [3 3].
%
% The rotation matrix defines rotations in a right-handed coordinate
% system, the positive direction is counter-clockwise, when looking from
% where the rotation axis points. To rotate any column vector use the
% following:
%   vp = rotM * v;
%
% To rotate matrices use the following command:
%   Ap = rotM * A * rotM';
%
% See also SW.GENMAGSTR.
%

if nargin==0
    help sw_rot
    return
end

% Normalize axis vector.
rotAxis = rotAxis./sqrt(sum(rotAxis.^2));
% 3x3 matrix to calculate Rodrigues' rotation formula.
nx  = [0 -rotAxis(3) rotAxis(2); rotAxis(3) 0 -rotAxis(1); -rotAxis(2) rotAxis(1) 0];
% Rodrigues' rotation formula.
rotM = eye(3)*cos(rotAngle) + sin(rotAngle)*nx + (1-cos(rotAngle))*(rotAxis')*rotAxis;

if nargin > 2
    V = (V'*rotM)';
else
    V = [];
end

end